package com.dissertation.action;


import com.alibaba.fastjson.JSON;
import com.dissertation.model.auth.User;
import com.dissertation.pojo.Message;
import com.dissertation.pojo.UserVO;
import com.dissertation.service.UserService;
import com.dissertation.utils.AuthUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static java.util.stream.Collectors.toList;

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    UserService userService;

    @PostMapping
    Message addUser(@RequestBody @Validated UserVO userVO , BindingResult result){
        if(result.hasErrors()){
            List<FieldError> fieldErrors = result.getFieldErrors();
            return Message.createErr( JSON.toJSONString( fieldErrors.stream()
                    .map( DefaultMessageSourceResolvable::getDefaultMessage )
                    .collect( toList() ) ) );
        }
        return Message.createSuc(userService.addUser(userVO));
    }

    @PutMapping
    Message changePwd(@RequestBody UserVO userVO ){
    return Message.createSuc(userService.changePwd(userVO.getUniqueName() , userVO.getPassword()));
    }


    @GetMapping
    public Message getName(){
        String name = AuthUtil.getUser().map(User::getName).orElse("请先登录");
        return Message.createSuc(name);
    }
}
